package com.example.shiro_realy.controller;

import com.example.shiro_realy.domian.JsonData;
import com.example.shiro_realy.domian.UserQuery;
import com.example.shiro_realy.service.UserSevice;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("pub")
public class PublicController {
    @RequestMapping("need_login")
    public JsonData needLogin(){
        return JsonData.buildSuccess("温馨提示：请使用对应的账号密码登录",-2);
    }

    @RequestMapping("not_permit")
    public JsonData notPermit(){
        return JsonData.buildSuccess("温馨提示：您没有权限访问该资源",-3);
    }

    @RequestMapping("index")
    public JsonData index(){
        return JsonData.buildSuccess("欢迎访问shiro-realy项目");
    }
    @PostMapping("login")
    public JsonData login(@RequestBody UserQuery userQuery, HttpServletRequest request, HttpServletResponse response){
        //获取登录主体
        Subject subject = SecurityUtils.getSubject();
        //创建放入内容的数组
        HashMap<String, Object> info = new HashMap<>();
        try {
            UsernamePasswordToken usernamePasswordToken =
                    new UsernamePasswordToken(userQuery.getName(), userQuery.getPwd());
            subject.login(usernamePasswordToken);
            info.put("mag","登录成功");
            //通过登录主体，获取sessionId，并将其填入到返回信息中
            info.put("session_id", subject.getSession().getId());

            return JsonData.buildSuccess(info);
        }catch (Exception e){
            e.printStackTrace();
            return JsonData.buildError("账号或密码错误");
        }
    }
}
